<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller as BaseController;
use App\Jobs\OrderSubmit;
use App\Libs\PhpOffice\Excel;
use App\Repository\Order\HistoryOrderRepository;
use App\Repository\UploadRepository;
use App\Repository\UpThree\MainOrderRepostition;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

// 分销商
class OrdersOldController extends BaseController
{
    private $repoist = null;
    private $disModel;
    private $infoModel;
    private $logModel;
    private $goodsModel;
    private $ordersUser;

    public function __construct(HistoryOrderRepository $HistoryOrderRepository)
    {
        $this->repoist = $HistoryOrderRepository;
    }

    public function store(Request $request)
    {
        return $this->repoist->add($request);
    }

    public function index(Request $request)
    {
        $where = [];
        if (!empty($request->get('order_num'))) {
            // $time = $request->get('dateRange');
            $where['like']['order_num'] = $request->get('order_num');
        }
        if (!empty($request->get('order'))) {
            // $time = $request->get('dateRange');
            $where['like']['order'] = $request->get('order');
        }
        if (!empty($request->get('page_name'))) {
            // $time = $request->get('dateRange');
            $where['like']['package_name'] = $request->get('page_name');
        }
        if (!empty($request->get('turn_page_name'))) {
            // $time = $request->get('dateRange');
            $where['like']['turn_package_name'] = $request->get('turn_page_name');
        }
        if (!empty($request->get('phone'))) {
            // $time = $request->get('dateRange');
            $where['like']['user_phone'] = $request->get('phone');
        }
        if (!empty($request->get('idcard'))) {
            // $time = $request->get('dateRange');
            $where['like']['user_idcard'] = $request->get('idcard');
        }
        if (!empty($request->get('name'))) {
            // $time = $request->get('dateRange');
            $where['like']['user_name'] = $request->get('name');
        }
        if (!empty($request->get('way'))) {
            // $time = $request->get('dateRange');
            $where['like']['channel'] = $request->get('way');
        }
        //时间验证
        if (!empty($request->get('dateRange'))) {
            // $time = $request->get('dateRange');
            $where['between'] = ['order_time' => $request->get('dateRange')];
        }
        // var_dump($where);
        // var_dump($where);
        $where['limit']['start'] = ($request->get('pageNum') - 1) * $request->get('pageSize');
        $where['limit']['number'] = $request->get('pageSize');
        // DB::connection()->enableQueryLog();
        // var_dump($request->user->shop_id, 1111111111);
        $data = $this->repoist->index($where, $request->user->shop_id);
        // $log = DB::getQueryLog();
        // var_dump($log);
        return $data;
    }

    public function indexDist(Request $request)
    {
        $request->offsetSet('is_dist', 1);
        $res = $this->index($request);
        // $data['']
        if (!empty($res['data'])) {
            foreach ($res['data'] as $key => &$v) {
                $resSouc = explode('.', $v['shop_name_str']);
                $resSouId = explode('.', $v['shop_id_str']);
                $v['source'] = '';
                if (empty($resSouId)) {
                    continue;
                }
                foreach ($resSouId as $keys => $val) {
                    if (!empty($val) && $val == $request->get('user')->shop_id) {
                        $v['source'] = !empty($resSouc[($keys + 1)]) ? $resSouc[($keys + 1)] : $v['shop_name'];
                    }
                }
                // if ($resSouId[1] != $request->get('user')->shop_id) {
                //   $v['channel_error_josn'] = '[]';
                // }
            }
        }
        return $res;
    }

    public function save(Request $request)
    {
        if (!$request->get('id')) {
            return $this->returnMsg(1, '请传递id参数');
        }
        $where = [
            'orders.id' => $request->get('id'),
            // 'shop_id' => $request->user->shop_id
        ];

        return $this->repoist->edit($where, $request);
    }

    public function saveUser(Request $request)
    {
        if (!$request->get('id')) {
            return $this->returnMsg(1, '请传递id参数');
        }
        $where = [
            'orders.id' => $request->get('id'),
            // 'shop_id' => $request->user->shop_id
        ];

        return $this->repoist->editUser($where, $request);
    }

    // 修改分销商的商品
    public function saveDist(Request $request)
    {
        if (!$request->get('id')) {
            return $this->returnMsg(1, '请传递id参数');
        }
        $where = [
            'orders.id' => $request->get('id'),
            // 'shop_id' => $request->user->shop_id
        ];
        if (!empty($request->get('goods_id'))) {
            $whereOrder = [
                'orders.id' => $request->get('id'),
            ];
            $resOrder = $this->repoist->getOne($whereOrder);
            if (!$resOrder) {
                return $this->returnMsg(101, '未查询到订单');
            }
            $whereGoods = [
                ['shop_id', '=', $resOrder['shop_id']],
                ['goods_str', 'like', '%.' . $request->get('goods_id') . '.%'],
            ];
            // var_dump($whereGoods);
            // 查询商品信息
            $isTrueGoods = $this->goodsModel->getOne($whereGoods);
            if (!$isTrueGoods) {
                return $this->returnMsg(101, '未查询到分销商的商品');
            }
            $request->offsetSet('goods_id', $isTrueGoods['id']);
        }
        return $this->repoist->edit($where, $request);
    }

    // 添加备注 和 修改备注
    public function orderRemark(Request $request)
    {
        $params = $request->all();
        if (empty($params['orderno'])) {
            return $this->returnMsg(100, '请刷新页面重试');
        }
        $where = [
            'orderno' => $params['orderno'],
        ];
        $whereOr = [
            ['shop_id', '=', $request->user->shop_id],
            ['shop_str', 'like', '%.' . $request->user->shop_id . '%'],
        ];
        //备注信息添加 和操作
        return $this->ordersUser->edit($where, $params, false, $whereOr);
    }

    public function getTaggingAll(Request $request)
    {
        if (!$request->get('goodsAllid')) {
            return $this->returnMsg(1, '请选中参数');
        }
        $goodsId = $request->get('goodsAllid');
        if (empty($goodsId)) {
            return $this->returnMsg(1, '请选中参数');
        }
        if (is_string($goodsId)) {
            $goodsId = explode(',', $goodsId);
        }
        if (!$request->get('goodsAllOrder')) {
            return $this->returnMsg(2, '请选中参数');
        }
        $allThree = $request->get('goodsAllOrder');
        if (empty($allThree)) {
            return $this->returnMsg(1, '请选中参数');
        }
        if (is_string($allThree)) {
            $allThree = explode(',', $allThree);
        }
        $tagging = $request->get('tagging');

        foreach ($allThree as $key => $v) {
            $where = [
                'orderno' => $v,
            ];
            $whereOr = [
                ['shop_id', '=', $request->user->shop_id],
                ['shop_str', 'like', '%.' . $request->user->shop_id . '%'],
            ];
            // 添加 限制 防止重复提交
            $isSubmit = Cache::get('orderid_isTransfer_tigging' . $v);
            if (!empty($isSubmit)) {
                continue;
            }
            if (empty($isSubmit)) {
                Cache::put('orderid_isTransfer_tigging' . $v, 1, Carbon::now()->addMinutes(1));
            }
            $res = $this->ordersUser->edit($where, ['tagging' => $tagging], false, $whereOr);
        }
        if (!empty($res)) {
            return $res;
        }
        return $this->returnMsg(100, '请刷新后再提交');
    }

    public function saveStatus(Request $request)
    {
        if (!$request->get('id')) {
            return $this->returnMsg(1, '请传递id参数');
        }
        $where = [
            'orders.id' => $request->get('id'),
            // 'shop_id' => $request->user->shop_id
        ];
        $whereOr = [
            ['orders.shop_id', '=', $request->user->shop_id],
            ['orders.shop_id_str', 'like', '%.' . $request->user->shop_id . '%'],
        ];
        return $this->repoist->editStatus($where, $request, $whereOr);
    }

    //  批量修改数据
    public function updateAllGoods(Request $request)
    {
        //
        if (!$request->get('goodsAllid')) {
            return $this->returnMsg(1, '请选中参数');
        }
        $goodsId = $request->get('goodsAllid');
        if (empty($goodsId)) {
            return $this->returnMsg(1, '请选中参数');
        }
        if (is_string($goodsId)) {
            $goodsId = explode(',', $goodsId);
        }
        if (!$request->get('goodsAllOrder')) {
            return $this->returnMsg(2, '请选中参数');
        }
        $allThree = $request->get('goodsAllOrder');
        if (empty($allThree)) {
            return $this->returnMsg(1, '请选中参数');
        }
        if (is_string($allThree)) {
            $allThree = explode(',', $allThree);
        }

        foreach ($goodsId as $key => $v) {
            $where = [
                'orders.id' => $v
            ];
            // 添加 限制 防止重复提交
            $isSubmit = Cache::get('orderid_isTransfer' . $v);
            if (!empty($isSubmit)) {
                continue;
            }
            if (empty($isSubmit)) {
                Cache::put('orderid_isTransfer' . $v, 1, Carbon::now()->addMinutes(1));
            }
            $res = $this->repoist->edit($where, $request);
            if (!empty($res['code']) && $res['code'] == 200 && !empty($res['data']['ordersno'])) {
                $isSubmit = Cache::get('orderid_isTransferDistBath' . $res['data']['ordersno']);
                if (!empty($isSubmit)) {
                    continue;
                }
                if (empty($isSubmit)) {
                    Cache::put('orderid_isTransferDistBath' . $res['data']['ordersno'], 1, Carbon::now()->addMinutes(1));
                }
                dispatch(new OrderSubmit($res['data']['ordersno'], 'batchAllGoods'))->onQueue('TaskOrderSubmitDispose');
            }
        }
        // foreach ($allThree as $key => $v) {
        //   // 加入到队列中重新提交  //batchAllGoods
        //   //// 添加 限制 防止重复提交
        //   $isSubmit = Cache::get('orderid_isTransferAll' . $v);
        //   if (!empty($isSubmit)) {
        //     continue;
        //   }
        //   if (empty($isSubmit)) {
        //     Cache::put('orderid_isTransferAll' . $v, 1, Carbon::now()->addMinutes(1));
        //   }
        //   dispatch(new OrderSubmit($v, 'batchAllGoods'))->onQueue('TaskOrderSubmitDispose');
        // }
        // var_dump($request->get('goodsAllid'));
        if (!empty($res)) {
            return $res;
        }
        return $this->returnMsg(100, '请刷新后再提交');
    }

    // 批量修改分销商的商品
    public function updateAllGoodsDist(Request $request)
    {
        $goodsId = $request->get('goods_id');
        if (empty($goodsId)) {
            return $this->returnMsg(101, '请选择修改的商品');
        }
        if (!$request->get('goodsAllid')) {
            return $this->returnMsg(1, '请选中参数');
        }
        $orderId = $request->get('goodsAllid');
        // 订单id
        if (empty($orderId)) {
            return $this->returnMsg(1, '请选中参数');
        }

        if (is_string($orderId)) {
            $orderId = explode(',', $orderId);
        }
        if (!$request->get('goodsAllOrder')) {
            return $this->returnMsg(2, '请选中参数');
        }
        $allThree = $request->get('goodsAllOrder');
        if (empty($allThree)) {
            return $this->returnMsg(1, '请选中参数');
        }
        if (is_string($allThree)) {
            $allThree = explode(',', $allThree);
        }
        $msg = '';
        foreach ($orderId as $key => $v) {
            $where = [
                'orders.id' => $v
            ];
            // 查询订单的店铺信息
            $isOrderTrue = $this->repoist->getOne($where);
            if (!$isOrderTrue) {
                $msg = '未查询到订单';
                continue;
            }

            $whereGoods = [
                ['shop_id', '=', $isOrderTrue['shop_id']],
                ['sup_goods_id_str', 'like', '%.' . $goodsId . '.%'],
            ];
            // 查询商品信息
            $isTrueGoods = $this->goodsModel->getOne($whereGoods);
            if (!$isTrueGoods) {
                $msg = '未查询到分销商的商品';
                continue;
            }
            $dataGoods = [
                'goods_id' => $isTrueGoods['id'],
            ];
            //// 添加 限制 防止重复提交
            $isSubmit = Cache::get('orderid_isTransferDist' . $v);
            if (!empty($isSubmit)) {
                continue;
            }
            if (empty($isSubmit)) {
                Cache::put('orderid_isTransferDist' . $v, 1, Carbon::now()->addMinutes(1));
            }
            $res = $this->repoist->edit($where, $dataGoods, false, true);
            // var_dump($res);
            // var_dump($res['data']['ordersno'], 44444444444);
            // die();
            if (!empty($res['code']) && $res['code'] == 200 && !empty($res['data']['ordersno'])) {
                $isSubmit = Cache::get('orderid_isTransferDistBath' . $res['data']['ordersno']);
                if (!empty($isSubmit)) {
                    continue;
                }
                if (empty($isSubmit)) {
                    Cache::put('orderid_isTransferDistBath' . $res['data']['ordersno'], 1, Carbon::now()->addMinutes(1));
                }
                dispatch(new OrderSubmit($res['data']['ordersno'], 'batchAllGoods'))->onQueue('TaskOrderSubmitDispose');
            }
        }
        // foreach ($allThree as $key => $v) {
        //   // 加入到队列中重新提交  //batchAllGoods
        //   //// 添加 限制 防止重复提交
        //   $isSubmit = Cache::get('orderid_isTransferDistBath' . $v);
        //   if (!empty($isSubmit)) {
        //     continue;
        //   }
        //   if (empty($isSubmit)) {
        //     Cache::put('orderid_isTransferDistBath' . $v, 1, Carbon::now()->addMinutes(1));
        //   }
        //   dispatch(new OrderSubmit($v, 'batchAllGoods'))->onQueue('TaskOrderSubmitDispose');
        // }
        // var_dump($request->get('goodsAllid'));
        if (!empty($res)) {
            return $res;
        }
        return $this->returnMsg(100, !empty($msg) ? $msg : '请刷新后再提交');
    }

    // 重新提交
    public function updateEditSubmit(Request $request)
    {

        if (!$request->get('goodsAllOrder')) {
            return $this->returnMsg(2, '请选中参数');
        }
        $allThree = $request->get('goodsAllOrder');
        if (empty($allThree)) {
            return $this->returnMsg(1, '请选中参数');
        }
        if (is_string($allThree)) {
            $allThree = explode(',', $allThree);
        }
        foreach ($allThree as $key => $v) {
            // 加入到队列中重新提交  //batchAllGoods
            $isSubmit = Cache::get('edit_isTransferDistBath' . $v);
            if (!empty($isSubmit)) {
                continue;
            }
            if (empty($isSubmit)) {
                Cache::put('edit_isTransferDistBath' . $v, 1, Carbon::now()->addMinutes(1));
            }
            dispatch(new OrderSubmit($v, 'batchAllGoods'))->onQueue('TaskOrderSubmitDispose');
        }
        // var_dump($request->get('goodsAllid'));
        // if (!empty($res)) {
        //   return $res;
        // }
        return $this->returnMsg(200, '已发出请求,稍后会提交');
    }

    public function show(Request $request, $id)
    {
        // $where = [
        //   'orders.id' => $id,

        // ];
        // 查询都要对应店铺
        $where = [
            ['orders.id', '=', $id],
        ];
        $whereOr = [

            ['orders.shop_str', 'like', '%.' . $request->user->shop_id . '.%'],
        ];
        $wheres = [
            ['orders.shop_id', '=', $request->user->shop_id],
        ];
        // $whereOrTwo = [

        //   ['orders.sup_shop_id', '=', $request->user->shop_id],
        // ];
        //查询一条数据
        $field = ['orders.id', 'orders_user.orderno', 'orders_user.contact_phone', 'orders_user.contact_name', 'orders_user.pay_name', 'orders_user.pay_phone', 'orders_user.pay_identity', 'orders_user.post_province', 'orders_user.post_city', 'orders_user.post_area', 'orders_user.post_address'];
        if (!empty($request->get('is_goods')) && $request->get('is_goods') == 1) {
            $field = ['orders.id', 'orders.ordersno as orderno', 'orders.goods_name', 'orders.goods_id', 'orders.goods_code', 'orders.product_id as product_ids', 'orders.product_name', 'orders.product_code', 'orders.sup_goods_id_str', 'orders.shop_id_str'];
        }
        if (!empty($request->get('is_goods')) && $request->get('is_goods') == 2) {
            $field = ['orders_user.id', 'orders.ordersno', 'orders_user.orderno', 'orders_user.remark', 'orders_user.tagging'];
        }
        // var_dump($where);
        // DB::connection()->enableQueryLog();
        $return = $this->repoist->getOne($where, $field, $whereOr, $wheres);
        // $logs = DB::getQueryLog();
        // var_dump($logs);
        if (!empty($request->get('is_goods')) && $request->get('is_goods') == 1 && !empty($return)) {
            if (!empty($return['shop_id_str'])) {
                $shopArr = explode('.', $return['shop_id_str']);
                $goodsArr = explode('.', $return['sup_goods_id_str']);
                foreach ($shopArr as $key => $v) {
                    if ($v == $request->user->shop_id) {
                        if (!empty($goodsArr[$key])) {
                            $return['goods_id'] = $goodsArr[$key];
                        }
                    }
                }
            }
        }
        if (!empty($return['goods_id'])) {
            $return['goods_id'] = (int)$return['goods_id'];
        }
        return $this->returnMsg(200, '查询成功', $return);
    }

    public function showOne($id)
    {
        $where = ['id' => $id];
        //查询一条数据
        $return = $this->repoist->getOne($where, ['id', 'goods_id', 'goods_name', 'goods_code']);
        return $this->returnMsg(200, '查询成功', $return);
    }

    // 修改备注
    public function showOneRemark($id)
    {
        $where = ['id' => $id];
        //查询一条数据
        $return = $this->repoist->getOne($where, ['id', 'remark']);
        return $this->returnMsg(200, '查询成功', $return);
    }

    public function listss(Request $request)
    {
        $where = [];
        if (!empty($request->get('name'))) {
            $where['where'] = ['name' => $request->get('name')];
        }

        $return = $this->repoist->lists($where);
        return $return;
    }

    public function destroy(Request $request, $id)
    {
        if (!$id) {
            return $this->returnMsg(1, '请传递参数');
        }
        $where = [
            'id' => $id,
            'shop_id' => $request->user->shop_id
        ];
        return $this->repoist->del($where);
    }

    // 导入功能
    public function import(Request $request)
    {
        $model = new UploadRepository();
        $res = $model->upload($request, 'file');
        if (empty($res['file_src'])) {
            return [
                'code' => 100,
                'msg' => '上传失败',
                'fileName' => ''
            ];
        }
        $request['file_name'] = $res['file_name'];
        $request['upload_rout'] = $res['file_src'];

        return $this->repoist->add($request);
    }

    public function getOrderStatus()
    {
        return $this->repoist->getOrderStatus();
    }

    public function getOrderSource()
    {
        return $this->repoist->getOrderSource();
    }

    //导出
    public function getOrderExcel(Request $request)
    {
        // pageNum  pageSize
        $request->offsetSet('pageSize', 99999);
        $request->offsetSet('pageNum', 1);
        $resData = $this->index($request);
        if (empty($resData['data'])) {
            return $this->returnMsg(100, '下载的数据不能为空');
        }
        $model = new Excel();
        $title = [
            '订单编号',
            '上游编号',
            '下游编号',
            '来源',
            '分销商',
            '用户姓名',
            '用户联系电话',
            '证件信息',
            '省',
            '市',
            '区',
            '详细地址',
            '订单状态'
        ];
        $excelData = [];
        foreach ($resData['data'] as $key => $v) {
            $excelData[] = [
                $v['orderno'],
                $v['sup_orderno'],
                $v['dist_orderno'],
                $v['source'],
                $v['shop_str'],
                $v['pay_name'],
                $v['pay_phone'],
                $v['pay_identity'] . ' ',
                $v['post_province'],
                $v['post_city'],
                $v['post_area'],
                $v['post_address'],
                $v['status_desc'],
            ];
        }
        $fielname = '/attach/excel/' . date('YmdHis') . '.xlsx';
        $model->exportFile($excelData, $title, $fielname);
        return $this->returnMsg(200, '导出成功', ['fiel' => $fielname]);
    }

    // 查询分销商
    public function getOrderDis(Request $request)
    {
        $shop_id = $request->user->shop_id;
        $where = [
            'supplier_id' => $shop_id,
        ];
        $field = ['shop_id as id', 'name'];
        $data = $this->disModel->getAllData($where, $field);
        return $this->returnMsg(200, '查询成功', $data);
    }

    // 查看提交详情
    public function getOrderRemark($id)
    {
        $where = ['orderno' => $id];
        $data = $this->logModel->getOne($where);
        return $this->returnMsg(200, '查询成功', $data);
    }

    // 查看详情
    public function getOrderInfo($id)
    {
        $where = ['orderno' => 'HK_' . $id];
        $data = $this->infoModel->getOne($where);
        return $this->returnMsg(200, '查询成功', $data);
    }

    //订单数据
    public function getOrderResubmit(Request $request)
    {
        if (empty($request->get('orderno'))) {
            return $this->returnMsg(1, '参数不能为空');
        }
        // return $this->returnMsg(1, '参数不能为空1111');
        $where = [
            'ordersno' => $request->get('orderno'),
        ];
        $model = new MainOrderRepostition();
        return $model->orderThree($where, true);
    }

    // 修改分销商 的数据
    public function updateEditDist(Request $request)
    {
        $params = $request->all();
        return $this->repoist->editDistAll($params);
    }
}
